/**
* @description: 714. 买卖股票的最佳时机含手续费
* @author hewei
* @date 2022/8/16 16:00
* @version 1.0
*/

public class MaxProfit3 {

    public static void main(String[] args) {
        int[] price = {1, 3, 2, 8, 4, 9};
        MaxProfit3 maxProfit3 = new MaxProfit3();
        System.out.println(maxProfit3.maxProfit(price, 2));
    }

    public int maxProfit1(int[] prices, int fee) {
        int n = prices.length;
        int[][] dp = new int[n][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0];
        for (int i = 1; i < n; i++) {
            int zero = dp[i - 1][0];
            int one = dp[i - 1][1];
            dp[i][0] = Math.max(one + prices[i] - fee, zero);
            dp[i][1] = Math.max(one, zero - prices[i]);
        }
        return dp[n - 1][0];
    }

    public int maxProfit(int[] prices, int fee) {
        int n = prices.length;
        int buy = fee + prices[0];
        int ans = 0;
        for (int i = 1; i < n; i++) {
            if (prices[i] > buy) {
                ans += prices[i] - buy;
                buy = prices[i];
            } else if (prices[i] < buy - fee) {
                buy = prices[i] + fee;
            }
        }
        return ans;
    }
}
